package com.chen.bpsptsystem;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;

/**
 * @CLASSNAME WebConfig
 * @DESCRIPTION 继承 SpringBootServletInitializer 相当于使用web.xml形式启动部署,配置http转https,
 * 导入证书resources里面 1122.p12,在application.yml配置ssl
 * ssl:
 *     key-store: classpath:1122.p12
 *     key-store-password:
 *     key-alias: tomcat
 * @AUTHOR chen
 * @DATE 2018-11-19 23:19
 **/
public class WebConfig extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources( BpsptsystemApplication.class );//使用web.xml 启动程序，指向BpsptsystemApplication，启动springboot项目
    }


    /*配置http自动转为https*/
    @Bean
    public ServletWebServerFactory servletWebServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint( "CONFIDENTIAL" );//机密的
                SecurityCollection securityCollection = new SecurityCollection();
                securityCollection.addPattern( "/*" );
                securityConstraint.addCollection( securityCollection );
                context.addConstraint( securityConstraint );
            }
        };
        factory.addAdditionalTomcatConnectors( httpConnector() );
        return factory;
    }

    //import org.apache.catalina.connector.Connector
    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector( "org.apache.coyote.http11.Http11NioProtocol" );
        connector.setScheme( "http" );
        connector.setPort( 8888 );
        connector.setSecure( false );
        connector.setRedirectPort( 8089 );//此处端口指定为8089  server:port: 8089

        return connector;
    }
}
